/**
 * 
 */
package org.mediahouse.trac;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.mediahouse.trac.http.AbstractCustomHttpServlet;
import org.mediahouse.trac.util.SimpleTextHtmlWriter;

/**
 * @author Tin
 * @version %I%, %G%
 * 
 */
@SuppressWarnings("serial")
public class TracManager extends AbstractCustomHttpServlet {

    /**
     * {@inheritDoc}
     * 
     * @see org.mediahouse.trac.http.AbstractCustomHttpServlet#doRequest(javax.servlet.http.HttpServletRequest,
     *      javax.servlet.http.HttpServletResponse,
     *      org.mediahouse.trac.http.CustomHttpServlet.HttpRequestMethodType)
     */
    @Override
    public void doRequest(final HttpServletRequest req,
            final HttpServletResponse resp, final HttpRequestMethodType method)
            throws IOException {

        final HttpSession session = req.getSession();
        switch (method) {

        /**
         * This {@code HttpServlet} class responds to all {@code GET} and
         * {@code POST} requests, and ignores any {@code PUT} or {@code DELETE}
         * HTTP request method types.
         */
        case GET:
        case POST:
            if (!ok(req)) {
                resp.setStatus(HttpServletResponse.SC_OK);
                this.redirect("/login", resp);

            } else {
                final SimpleTextHtmlWriter out = new SimpleTextHtmlWriter(resp.getWriter());
                try {
                    resp.setContentType("text/html");
                    resp.setStatus(HttpServletResponse.SC_OK);
                    out.h1("Welcome to Trac, " + session.getAttribute("name"));
                    out.p("Logged in as " + session.getAttribute("token"));
                } finally {
                    out.close();
                }
            }
            return;
        }
    }

    private boolean ok(final HttpServletRequest req) {
        return req.getSession().getAttribute("token") != null;
    }

}
